package com.yy.wga.common.util;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

/**
 * SpEL表达式解析器
 *
 * @author lgw
 */
public class SpelUtils {

    /**
     * SpEL表达式解析器
     */
    private static final ExpressionParser expressionParser = new SpelExpressionParser();
    /**
     * 上下文
     */
    private static final ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer();

    public static String getSpelValue(String expression, ProceedingJoinPoint joinPoint) {
        // 获取方法参数
        Object[] args = joinPoint.getArgs();

        // 获取方法参数名称
        String[] parameterNames = parameterNameDiscoverer.getParameterNames(((MethodSignature) joinPoint.getSignature()).getMethod());
        EvaluationContext evaluationContext = new StandardEvaluationContext();
        for (int i = 0; i < args.length; i++) {
            // 将方法参数及其属性值添加到上下文中
            evaluationContext.setVariable(parameterNames[i], args[i]);
        }
        // 解析并计算SpEL表达式的值
        return expressionParser.parseExpression(expression).getValue(evaluationContext, String.class);

    }
}
